package com.gxa.interimpl;

import com.gxa.entity.*;
import com.gxa.inter.OpenvasToolInter;
import com.gxa.util.OpenvasStatusException;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.xml.sax.InputSource;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.*;

public class OpenvasTool implements OpenvasToolInter {
    //ִ������

    private static String execCMD(String command) throws Exception {
        StringBuilder sb = new StringBuilder();
        String[] cmdA = {"/bin/sh", "-c", "docker exec -it openvas " + command};
        Process process;
        process = Runtime.getRuntime().exec(cmdA);
        //ȡ���������������
        InputStream fis = process.getInputStream();
        //��һ�����������ȥ��  
        //�û���������  
        BufferedReader br = new BufferedReader(new InputStreamReader(fis, "GB2312"));
        String line = null;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        return sb.toString();
    }

    //SAXBuilder��ȡDocument����
    private Document getDocument(String xmlstring) throws Exception {
        StringReader read = new StringReader(xmlstring);
        InputSource source = new InputSource(read);
        //analysis
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(source);
        return doc;
    }

    //�ж�״̬��
    private void judgeStatus(Element root) throws Exception {
        String status = root.getAttributeValue("status");//���ص�״̬�룺200�ɹ� 404not found
        String statusText = root.getAttributeValue("status_text");//���ص�״̬��Ϣ
        switch (status) {
            case "200":
            case "201":
            case "202":
                break;
            default:
                throw new OpenvasStatusException(statusText);
        }
    }

    @Override
    public List<Map<String, Object>> getPortList() throws Exception {
        //�洢��ʽΪ��[{name:name,comment:comment,...},{},{},...]
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<get_port_lists details=\"1\" targets=\"1\"/>");
        String xmlString = execCMD("omp -u admin -w 1234 --xml='" + xmlcmd + "'");
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);//�жϷ��ص�״̬��
        //��ȡportList�ӽڵ��б�
        List<Element> portlist = root.getChildren("port_list");
        //����portList
        for (int i = 0; i < portlist.size(); i++) {
            Element e = portlist.get(i);
            Map<String, Object> mape = new HashMap<String, Object>();
            String portId = e.getAttributeValue("id");
            String name = e.getChildText("name");
            String allcount = e.getChild("port_count").getChildText("all");//�˿�����
            String tcpcount = e.getChild("port_count").getChildText("tcp");//tcp�˿���
            String udpcount = e.getChild("port_count").getChildText("udp");//udp�˿���
            mape.put("portId", portId);
            mape.put("name", name);
            mape.put("allcount", allcount);
            mape.put("tcpcount", tcpcount);
            mape.put("udpcount", udpcount);
            resultList.add(mape);
        }
        return resultList;
    }

    @Override
    public Map<String, Object> getOnePortListRanges(String portlistId) throws Exception {
        //�洢��ʽΪ��name��name,comment:comment,rangelist:[{},{},{}];
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<get_port_lists port_list_id='" + portlistId + "' details=\"1\" targets=\"1\"/>");
        String xmlString = execCMD("omp -u admin -w 1234 --xml='" + xmlcmd + "'");
        Map<String, Object> resultmap = new HashMap<String, Object>();
        //try {
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);//�жϷ��ص�״̬��
        Element portele = root.getChild("port_list");
        String name = portele.getChildText("name");
        String comment = portele.getChildText("comment");
        Element portranges = portele.getChild("port_ranges");
        //��ȡport_ranges�ӽڵ��б�
        List<Element> rangeslist = portranges.getChildren("port_range");
        //list�洢port_ranges�ӽڵ�����
        List<Map<String, Object>> rangeList = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < rangeslist.size(); i++) {
            Element e = rangeslist.get(i);
            String rangeId = e.getAttributeValue("id");
            Map<String, Object> rmap = new HashMap<String, Object>();
            String type = e.getChildText("type");//range ���ͣ�tcp/udp
            String start = e.getChildText("start");//range ��ʼ�˿�
            String end = e.getChildText("end");//range �����˿�
            String rcomment = e.getChildText("comment");
            rmap.put("rangeid", rangeId);
            rmap.put("type", type);
            rmap.put("start", start);
            rmap.put("end", end);
            rmap.put("rcomment", rcomment);
            rangeList.add(rmap);
        }
        resultmap.put("name", name);
        resultmap.put("comment", comment);
        resultmap.put("rangeslist", rangeList);
		/*}catch(Exception e) {
			e.printStackTrace();
		}*/
        return resultmap;
    }

    @Override
    public void createPortRanges(String portId, String type, String start, String end) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<create_port_range>");
        xmlcmd.append("<port_list id='" + portId + "'>");
        xmlcmd.append("<start>" + start + "</start>");
        xmlcmd.append("<end>" + end + "</end>");
        xmlcmd.append("<type>" + type + "</type>");
        xmlcmd.append("</create_port_range>");
        String xmlString = execCMD("omp -u admin -w 1234 --xml='" + xmlcmd + "'");
        //try {
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
		/*}catch(Exception e) {
		/	e.printStackTrace();
		}*/
    }

    @Override
    public void createPortList(String name, String comment, String port_range) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<create_port_list>");
        xmlcmd.append("<name>" + name + "</name>");
        xmlcmd.append("<comment>" + comment + "</comment>");
        xmlcmd.append("<port_range>" + port_range + "</port_range>");
        xmlcmd.append("</create_port_list>");
        String xmlString = execCMD("omp -u admin -w 1234 --xml='" + xmlcmd + "'");
        //try {
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
		/*} catch (Exception e) {
			e.printStackTrace();
		}*/
    }

    @Override
    public void deletePortRanges(String portrangeId) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<delete_port_range port_range_id='" + portrangeId + "'/>");
        String xmlString = execCMD("omp -u admin -w 1234 --xml='" + xmlcmd + "'");
        //try {
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
		/*} catch (Exception e) {
			e.printStackTrace();
			return false;
		}*/
    }

    @Override
    public void deletePortList(String portId) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<delete_port_list port_list_id='" + portId + "'/>");
        String xmlString = execCMD("omp -u admin -w 1234 --xml='" + xmlcmd + "'");
        //try {
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
		/*} catch (Exception e) {
			e.printStackTrace();
			return false;
		}*/
    }

    @Override
    public List<TargetEntity> getTargetList() throws Exception {
        //�洢��ʽ��[{name��name,comment:comment,credential:[{},{},{}]}��{}��{}��������]
        StringBuilder xmlcmd = new StringBuilder();
        List<TargetEntity> resultList = new ArrayList<TargetEntity>();
        xmlcmd.append("<get_targets/>");
        String xmlString = execCMD("omp -u admin -w 1234 --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
        List<Element> targetList = root.getChildren("target");
        for (int i = 0; i < targetList.size(); i++) {
            TargetEntity target = new TargetEntity();
            Element e = targetList.get(i);
            String tId = e.getAttributeValue("id");//targetId
            String name = e.getChildText("name");//target����
            String comment = e.getChildText("comment");//target����
            String hosts = e.getChildText("hosts");//Ŀ��������ַ
            String excludeHosts = e.getChildText("exclude_hosts");//�ų�������ַ
            //��ȡportlist id
            Element port = e.getChild("port_list");
            String portId = port.getAttributeValue("id");//�˿��б�ID
            //��ȡƾ֤
            Element ssh_credential = e.getChild("ssh_credential");
            Element smbCredential = e.getChild("smbCredential");
            Element esxiCredential = e.getChild("esxiCredential");
            Element snmpCredential = e.getChild("snmpCredential");
            String sshId = ssh_credential.getAttributeValue("id");
            String smbId = smbCredential.getAttributeValue("id");
            String esxiId = esxiCredential.getAttributeValue("id");
            String snmpId = snmpCredential.getAttributeValue("id");

            String reverseLookupOnly = e.getChildText("reverse_lookup_only");
            String reverseLookupUnify = e.getChildText("reverse_lookup_unify");
            String aliveTests = e.getChildText("alive_tests");

            target.setUuid(tId);
            target.setName(name);
            target.setComment(comment);
            target.setHosts(hosts);
            target.setExclude_hosts(excludeHosts);
            target.setPortId(portId);
            target.setSsh_lsc_credential(sshId);
            target.setSmb_lsc_credential(smbId);
            target.setEsxi_lsc_credential(esxiId);
            target.setReverse_lookup_only(reverseLookupOnly);
            target.setReverse_lookup_unify(reverseLookupUnify);
            target.setAlive_tests(aliveTests);

            resultList.add(target);
        }
        return resultList;
    }

    @Override
    public TargetEntity getOneTarget(String targetId) throws Exception {
        //�洢��ʽ��[{name��name,comment:comment,credential:[{},{},{}]}��{}��{}��������]
        StringBuilder xmlcmd = new StringBuilder();
        TargetEntity result = new TargetEntity();
        xmlcmd.append("<get_targets target_id='" + targetId + "'/>");
        String xmlString = execCMD("omp -u admin -w 1234 --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
        Element etarget = root.getChild("target");
        String tId = etarget.getAttributeValue("id");//targetId
        String name = etarget.getChildText("name");//target����
        String comment = etarget.getChildText("comment");//target����
        String hosts = etarget.getChildText("hosts");//Ŀ��������ַ
        String excludeHosts = etarget.getChildText("exclude_hosts");//�ų�������ַ
        //��ȡportlist id
        Element port = etarget.getChild("port_list");
        String portId = port.getAttributeValue("id");//�˿��б�ID
        //��ȡƾ֤
        Element ssh_credential = etarget.getChild("ssh_credential");
        Element smbCredential = etarget.getChild("smbCredential");
        Element esxiCredential = etarget.getChild("esxiCredential");
        Element snmpCredential = etarget.getChild("snmpCredential");
        String sshId = ssh_credential.getAttributeValue("id");
        String smbId = smbCredential.getAttributeValue("id");
        String esxiId = esxiCredential.getAttributeValue("id");
        String snmpId = snmpCredential.getAttributeValue("id");
        String reverseLookupOnly = etarget.getChildText("reverse_lookup_only");
        String reverseLookupUnify = etarget.getChildText("reverse_lookup_unify");
        String aliveTests = etarget.getChildText("alive_tests");

        result.setUuid(tId);
        result.setName(name);
        result.setComment(comment);
        result.setHosts(hosts);
        result.setExclude_hosts(excludeHosts);
        result.setPortId(portId);
        result.setSsh_lsc_credential(sshId);
        result.setSmb_lsc_credential(smbId);
        result.setEsxi_lsc_credential(esxiId);
        result.setReverse_lookup_only(reverseLookupOnly);
        result.setReverse_lookup_unify(reverseLookupUnify);
        result.setAlive_tests(aliveTests);
        return result;
    }

    @Override
    public void createTarget(TargetEntity target) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<create_target>");
        xmlcmd.append("<name>" + target.getName() + "</name>");
        xmlcmd.append("<hosts>" + target.getHosts() + "</hosts>");
        xmlcmd.append("<reverse_lookup_only>" + target.getReverse_lookup_only() + "</reverse_lookup_only>");
        xmlcmd.append("<reverse_lookup_unify>" + target.getReverse_lookup_unify() + "</reverse_lookup_unify>");
        xmlcmd.append("<port_list id='" + target.getPortId() + "'/>");
        xmlcmd.append("<alive_tests>" + target.getAlive_tests() + "</alive_tests>");
        if (target.getExclude_hosts() != null && !target.getExclude_hosts().isEmpty()) {
            xmlcmd.append("<exclude_hosts>" + target.getExclude_hosts() + "</exclude_hosts>");
        }
        if (target.getComment() != null && !target.getComment().isEmpty()) {
            xmlcmd.append("<comment>" + target.getComment() + "</comment>");
        }
        if (target.getSsh_lsc_credential() != null && !target.getSsh_lsc_credential().isEmpty()) {
            xmlcmd.append("<ssh_lsc_credential id='" + target.getSsh_lsc_credential() + "'>");
            if (target.getSsh_port() != null && !target.getSsh_port().isEmpty()) {
                xmlcmd.append("<port>" + target.getSsh_port() + "</port>");
            }
            xmlcmd.append("</ssh_lsc_credential>");
        }
        if (target.getSmb_lsc_credential() != null && !target.getSmb_lsc_credential().isEmpty()) {
            xmlcmd.append("<smb_lsc_credential id='" + target.getSmb_lsc_credential() + "'/>");
        }
        if (target.getEsxi_lsc_credential() != null && !target.getEsxi_lsc_credential().isEmpty()) {
            xmlcmd.append("<esxi_lsc_credential id='" + target.getEsxi_lsc_credential() + "'/>");
        }
        xmlcmd.append("</create_target>");
        String xmlString = execCMD("omp -u admin -w 1234 --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
    }

    @Override
    public void deleteTarget(String targetId) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<delete_target target_id='" + targetId + "'/>");
        String xmlString = execCMD("omp -u admin -w 1234 --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
    }

    @Override
    public void modifyTarget(TargetEntity target) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<modify_target target_id='" + target.getUuid() + "'>");
        xmlcmd.append("<name>" + target.getName() + "</name>");
        xmlcmd.append("<hosts>" + target.getHosts() + "</hosts>");
        xmlcmd.append("<reverse_lookup_only>" + target.getReverse_lookup_only() + "</reverse_lookup_only>");
        xmlcmd.append("<reverse_lookup_unify>" + target.getReverse_lookup_unify() + "</reverse_lookup_unify>");
        xmlcmd.append("<port_list id='" + target.getPortId() + "'/>");
        xmlcmd.append("<alive_tests>" + target.getAlive_tests() + "</alive_tests>");
        if (target.getExclude_hosts() != null && !target.getExclude_hosts().isEmpty()) {
            xmlcmd.append("<exclude_hosts>" + target.getExclude_hosts() + "</exclude_hosts>");
        }
        if (target.getComment() != null && !target.getComment().isEmpty()) {
            xmlcmd.append("<comment>" + target.getComment() + "</comment>");
        }
        if (target.getSsh_lsc_credential() != null && !target.getSsh_lsc_credential().isEmpty()) {
            xmlcmd.append("<ssh_lsc_credential id='" + target.getSsh_lsc_credential() + "'>");
            if (target.getSsh_port() != null && !target.getSsh_port().isEmpty()) {
                xmlcmd.append("<port>" + target.getSsh_port() + "</port>");
            }
            xmlcmd.append("</ssh_lsc_credential>");
        }
        if (target.getSmb_lsc_credential() != null && !target.getSmb_lsc_credential().isEmpty()) {
            xmlcmd.append("<smb_lsc_credential id='" + target.getSmb_lsc_credential() + "'/>");
        }
        if (target.getEsxi_lsc_credential() != null && !target.getEsxi_lsc_credential().isEmpty()) {
            xmlcmd.append("<esxi_lsc_credential id='" + target.getEsxi_lsc_credential() + "'/>");
        }
        xmlcmd.append("</modify_target>");
        String xmlString = execCMD("omp -u admin -w 1234 --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
    }

    @Override
    public void createTask(TaskEntity task) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<create_task>");
        xmlcmd.append("<name>" + task.getName() + "</name>");
        xmlcmd.append("<config id='" + task.getConfigId() + "'/>");
        xmlcmd.append("<target id='" + task.getTargetId() + "'/>");
        xmlcmd.append("<scanner id='" + task.getScannerId() + "'/>");
        xmlcmd.append("</create_task>");
        String xmlString = execCMD("omp -u admin -w 1234 --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
    }

    @Override
    public String startTask(String taskId) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<start_task task_id='" + taskId + "'/>");
        String xmlString = execCMD("omp -u admin -w 1234 --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
        //���ر���Id
        String reportId = root.getChildText("report_id");
        return reportId;
    }

    @Override
    public String startWizardTask(String host) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<run_wizard>");
        xmlcmd.append("<name>����ɨ��-" + host + "</name>");
        xmlcmd.append("<params>");
        xmlcmd.append("<param>");
        xmlcmd.append("<name>hosts</name>");
        xmlcmd.append("<value>" + host + "</value>");
        xmlcmd.append("</param>");
        xmlcmd.append("</params>");
        xmlcmd.append("</run_wizard>");
        String xmlString = execCMD("omp -u admin -w 1234 --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
        Element startroot = root.getChild("response").getChild("start_task_response ");
        judgeStatus(startroot);
        //���ر���Id
        String reportId = startroot.getChildText("report_id");
        return reportId;
    }

    @Override
    public void stopTask(String taskId) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<stop_task task_id='" + taskId + "'/>");
        String xmlString = execCMD("omp -u admin -w 1234 --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
    }

    @Override
    public void modifyPortList(String portId, String name, String comment) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<modify_port_list port_list_id='" + portId + "'>");
        xmlcmd.append("<name>" + name + "</name>");
        xmlcmd.append("<comment>" + comment + "</comment>");
        xmlcmd.append("</modify_port_list>");
        String xmlString = execCMD("omp -u admin -w 1234 --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
    }

    @Override
    public List<ConfigEntity> getConfigList() throws Exception {
        //�洢��ʽ��[{id:id,name:name},{},{}...]
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<get_configs/>");
        String xmlString = execCMD("omp -u admin -w 1234 --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
        List<Element> configlist = root.getChildren("config");
        List<ConfigEntity> resultList = new ArrayList<ConfigEntity>();
        for (int i = 0; i < configlist.size(); i++) {
            Element e = configlist.get(i);
            ConfigEntity config = new ConfigEntity();
            String configId = e.getAttributeValue("id");
            String name = e.getChildText("name");
            config.setId(configId);
            config.setName(name);
            resultList.add(config);
        }
        return resultList;
    }

    @Override
    public List<TaskInfoEntity> getTasksList() throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<get_tasks/>");
        String xmlString = execCMD("omp -u admin -w 1234 --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
        List<Element> tasklist = root.getChildren("task");
        List<TaskInfoEntity> resultList = new ArrayList<TaskInfoEntity>();
        for (int i = 0; i < tasklist.size(); i++) {
            Element e = tasklist.get(i);
            String tId = e.getAttributeValue("id");
            String name = e.getChildText("name");
            String checkTime = e.getChildText("modification_time");
            String configId = e.getChild("config").getAttributeValue("id");
            String targetId = e.getChild("target").getAttributeValue("id");
            String status = e.getChildText("status");
            switch (status) {
                case "Done":
                    status = "�����";
                    break;
                case "Running":
                    status = e.getChildText("progress") + "%";
                    break;
                case "Stopped":
                    status = "��ֹ";
                    break;
                default:
                    status = "�ȴ���";
                    break;
            }
            Element reportInfo = e.getChild("first_report").getChild("report");
            Element resultInfo = reportInfo.getChild("result_count");
            String severity = reportInfo.getChildText("severity");
            int debugCount = Integer.parseInt(resultInfo.getChildText("debug"));
            int holeCount = Integer.parseInt(resultInfo.getChildText("hole"));
            int infoCount = Integer.parseInt(resultInfo.getChildText("info"));
            int logCount = Integer.parseInt(resultInfo.getChildText("log"));
            int warningCount = Integer.parseInt(resultInfo.getChildText("warning"));
            int falsePositiveCount = Integer.parseInt(resultInfo.getChildText("false_positive"));
            int resultcount = debugCount + holeCount + infoCount + logCount + warningCount + falsePositiveCount;
            TaskInfoEntity task = new TaskInfoEntity();
            task.setTaskId(tId);
            task.setName(name);
            task.setConfigId(configId);
            task.setTargetId(targetId);
            task.setStatus(status);
            task.setSeverity(severity);
            task.setResultcount(resultcount);
            //ת��ʱ��
            SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);//����ı�ת����ʱ���ʽ
            SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//��Ҫת���ɵ�ʱ���ʽ
            Date checkDate = dff.parse(checkTime);
            String ctime = df1.format(checkDate);
            task.setCheckTime(ctime);
            resultList.add(task);
        }
        return resultList;
    }

    @Override
    public TaskInfoEntity getOneTask(String taskId) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<get_tasks task_id='" + taskId + "'/>");
        String xmlString = execCMD("omp -u admin -w 1234 --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
        Element etask = root.getChild("task");
        TaskInfoEntity result = new TaskInfoEntity();
        String tId = etask.getAttributeValue("id");
        String name = etask.getChildText("name");
        String checkTime = etask.getChildText("modification_time");
        String configId = etask.getChild("config").getAttributeValue("id");
        String targetId = etask.getChild("target").getAttributeValue("id");
        String status = etask.getChildText("status");
        switch (status) {
            case "Done":
                status = "�����";
                break;
            case "Running":
                status = etask.getChildText("progress") + "%";
                break;
            case "Stopped":
                status = "��ֹ";
                break;
            default:
                status = "�ȴ���";
                break;
        }
        Element reportInfo = etask.getChild("first_report").getChild("report");
        Element resultInfo = reportInfo.getChild("result_count");
        String severity = reportInfo.getChildText("severity");
        int debugCount = Integer.parseInt(resultInfo.getChildText("debug"));
        int holeCount = Integer.parseInt(resultInfo.getChildText("hole"));
        int infoCount = Integer.parseInt(resultInfo.getChildText("info"));
        int logCount = Integer.parseInt(resultInfo.getChildText("log"));
        int warningCount = Integer.parseInt(resultInfo.getChildText("warning"));
        int falsePositiveCount = Integer.parseInt(resultInfo.getChildText("false_positive"));
        int resultcount = debugCount + holeCount + infoCount + logCount + warningCount + falsePositiveCount;
        result.setTaskId(tId);
        result.setName(name);
        result.setConfigId(configId);
        result.setTargetId(targetId);
        result.setStatus(status);
        result.setSeverity(severity);
        result.setResultcount(resultcount);
        //ת��ʱ��
        SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);//����ı�ת����ʱ���ʽ
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//��Ҫת���ɵ�ʱ���ʽ
        Date checkDate = dff.parse(checkTime);
        String ctime = df1.format(checkDate);
        result.setCheckTime(ctime);
        return result;
    }

    @Override
    public void createUser(String userName) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<create_user>");
        xmlcmd.append("<name>" + userName + "</name>");
        xmlcmd.append("<password>123456</password>");
        xmlcmd.append("<role id=\"7a8cb5b4-b74d-11e2-8187-406186ea4fc5\"/>");
        xmlcmd.append("</create_user>");
        String xmlString = execCMD("omp -u admin -w 1234 --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
    }

    @Override
    public void authenticateUser(UserEntity user) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<authenticate>");
        xmlcmd.append("<credentials>");
        xmlcmd.append("<username>" + user.getUsername() + "</username>");
        xmlcmd.append("<password>" + user.getPassword() + "</password>");
        xmlcmd.append("</credentials>");
        xmlcmd.append("</authenticate>");
        String xmlString = execCMD("omp -u admin -w 1234 --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
    }

    @Override
    public void deleteUser(UserEntity user) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<delete_user name='" + user.getUsername() + "'/>");
        String xmlString = execCMD("omp -u admin -w 1234 --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
    }

    @Override
    public void deleteTask(String taskId) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<delete_task task_id='" + taskId + "'/>");
        String xmlString = execCMD("omps -u admin -w 1234 --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
    }

    @Override
    public Map<String, Object> getReport(String reportId) throws Exception {
        //�洢��ʽ��{count:count,results:[{},{},{}....]}
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<get_reports report_id='" + reportId + "'/>");
        String xmlString = execCMD("omps -u admin -w 1234 --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
        Element reportInfo = root.getChild("report").getChild("report");
        //�����Ŀ
        Element resultCountInfo = reportInfo.getChild("result_count");
        int debugCount = Integer.parseInt(resultCountInfo.getChild("debug").getChildText("full"));
        int holeCount = Integer.parseInt(resultCountInfo.getChild("hole").getChildText("full"));
        int infoCount = Integer.parseInt(resultCountInfo.getChild("info").getChildText("full"));
        int logCount = Integer.parseInt(resultCountInfo.getChild("log").getChildText("full"));
        int warningCount = Integer.parseInt(resultCountInfo.getChild("warning").getChildText("full"));
        int falsePositiveCount = Integer.parseInt(resultCountInfo.getChild("false_positive").getChildText("full"));
        Map<String, Object> resultmap = new HashMap<String, Object>();
        resultmap.put("debugCount", debugCount);
        resultmap.put("holeCount", holeCount);
        resultmap.put("infoCount", infoCount);
        resultmap.put("logCount", logCount);
        resultmap.put("warningCount", warningCount);
        resultmap.put("falsePositiveCount", falsePositiveCount);
        List<Map<String, Object>> resultInfoList = new ArrayList<Map<String, Object>>();
        //result�����Ϣ
        Element resultsInfo = reportInfo.getChild("results");
        List<Element> results = resultsInfo.getChildren("result");
        for (int i = 0; i < results.size(); i++) {
            Element e = results.get(i);
            Map<String, Object> eresultmap = new HashMap<String, Object>();
            String resultId = e.getAttributeValue("id");
            String name = e.getChildText("name");
            String host = e.getChildText("host");
            String port = e.getChildText("port");
            String severity = e.getChildText("severity");
            String threat = e.getChildText("threat");
            switch (threat) {
                case "Medium":
                    threat = "��";
                    break;
                case "High":
                    threat = "��";
                    break;
                case "Log":
                    break;
                default:
                    break;
            }
            String qod = e.getChild("qod").getChildText("value");
            eresultmap.put("resultId", resultId);
            eresultmap.put("name", name);
            eresultmap.put("host", host);
            eresultmap.put("port", port);
            eresultmap.put("severity", severity);
            eresultmap.put("threat", threat);
            eresultmap.put("qod", qod);
            resultInfoList.add(eresultmap);
        }
        resultmap.put("results", resultInfoList);
        return resultmap;
    }

    @Override
    public Map<String, Object> getReportResult(String resultId) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<get_results result_id='" + resultId + "'/>");
        String xmlString = execCMD("omps -u admin -w 1234 --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Element resultInfo = root.getChild("result");
        String name = resultInfo.getChildText("name");
        String qod = resultInfo.getChild("qod").getChildText("value");
        String host = resultInfo.getChildText("host");
        String port = resultInfo.getChildText("port");

        resultMap.put("name", name);//����
        resultMap.put("qod", qod);//����
        resultMap.put("host", host);//Ŀ������
        resultMap.put("port", port);//�˿�

        Element nvtInfo = resultInfo.getChild("nvt");
        String cvss = nvtInfo.getChildText("cvss_base");//cvss ����
        String cve = nvtInfo.getChildText("cve");
        String xref = nvtInfo.getChildText("xref");//Other:Xref
        String[] xrefs = xref.split(",");
        Element certInfo = nvtInfo.getChild("cert");
        List<Element> certList = certInfo.getChildren("cert_ref");
        String certs = "";
        for (int i = 0; i < certList.size(); i++) {
            String id = certList.get(i).getAttributeValue("id");
            certs += id + ",";
        }
        certs = certs.substring(0, certs.length() - 1);
        String scanNvtVersion = resultInfo.getChildText("scan_nvt_version");
        resultMap.put("cvss", cvss);
        resultMap.put("cve", cve);
        resultMap.put("xrefs", xrefs);
        resultMap.put("certs", certs);
        resultMap.put("scanNvtVersion", scanNvtVersion);

        String tags = nvtInfo.getChildText("tags");
        String[] tagsArray = tags.split("|");
        for (int i = 0; i < tagsArray.length; i++) {
            String estr = tagsArray[i];
            if (estr.contains("summary=")) {
                String summaryStr = estr.substring(estr.lastIndexOf("=") + 1, estr.length());// ժҪ
                resultMap.put("summary", summaryStr);
            } else if (estr.contains("impact=")) {
                String impactStr = estr.substring(estr.lastIndexOf("=") + 1, estr.length());// Ӱ��
                resultMap.put("impact", impactStr);
            } else if (estr.contains("solution=")) {
                String solutionStr = estr.substring(estr.lastIndexOf("=") + 1, estr.length());// �������
                resultMap.put("solution", solutionStr);
            } else if (estr.contains("solution_type=")) {
                String solutionTypeStr = estr.substring(estr.lastIndexOf("=") + 1, estr.length());// �������
                resultMap.put("solutionType", solutionTypeStr);
            } else if (estr.contains("affected=")) {
                String affectedStr = estr.substring(estr.lastIndexOf("=") + 1, estr.length());// ��Ӱ���ϵͳ
                resultMap.put("affected", affectedStr);
            }
        }
        return resultMap;
    }

    @Override
    public void createCredentials(CredentialsEntity credentials) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<create_lsc_credential>");
        xmlcmd.append("<name>" + credentials.getName() + "</name>");
        xmlcmd.append("<login>" + credentials.getLogin() + "</login>");
        xmlcmd.append("<password>" + credentials.getPassword() + "</password>");
        xmlcmd.append("<comment>" + credentials.getComment() + "</comment>");
        xmlcmd.append("</create_lsc_credential>");
        String xmlString = execCMD("omps -u admin -w 1234 --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);

    }

    @Override
    public List<CredentialsEntity> getCredentialsList() throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<get_credentials/>");
        String xmlString = execCMD("omps -u admin -w 1234 --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
        List<CredentialsEntity> resultList = new ArrayList<CredentialsEntity>();
        List<Element> credentialList = root.getChildren("credential");
        for (int i = 0; i < credentialList.size(); i++) {
            CredentialsEntity credential = new CredentialsEntity();
            Element e = credentialList.get(i);
            String credentialId = e.getAttributeValue("id");
            String name = e.getChildText("name");
            String fullType = e.getChildText("full_type");
            String login = e.getChildText("login");
            int allowInsecure = Integer.parseInt(e.getChildText("allow_insecure"));
            String comment = e.getChildText("comment");

            credential.setUuid(credentialId);
            credential.setName(name);
            credential.setFullType(fullType);
            credential.setLogin(login);
            credential.setAllow_insecure(allowInsecure);
            credential.setComment(comment);

            resultList.add(credential);
        }
        return resultList;
    }

    @Override
    public CredentialsEntity getOneCredential(String cId) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<get_credentials credential_id='" + cId + "'/>");
        String xmlString = execCMD("omps -u admin -w 1234 --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
        CredentialsEntity result = new CredentialsEntity();
        Element ecredential = root.getChild("credential");
        String credentialId = ecredential.getAttributeValue("id");
        String name = ecredential.getChildText("name");
        String fullType = ecredential.getChildText("full_type");
        String login = ecredential.getChildText("login");
        int allowInsecure = Integer.parseInt(ecredential.getChildText("allow_insecure"));
        String comment = ecredential.getChildText("comment");

        result.setUuid(credentialId);
        result.setName(name);
        result.setFullType(fullType);
        result.setLogin(login);
        result.setAllow_insecure(allowInsecure);
        result.setComment(comment);

        return result;
    }

    @Override
    public void modifyCredentials(CredentialsEntity credentials) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<modify_credential credential_id='" + credentials.getUuid() + "'>");
        xmlcmd.append("<comment>" + credentials.getComment() + "</comment>");
        xmlcmd.append("<name>" + credentials.getName() + "</name>");
        xmlcmd.append("<password>" + credentials.getPassword() + "</password>");
        xmlcmd.append("<login>" + credentials.getLogin() + "</login>");
        xmlcmd.append("</modify_credential>");

        String xmlString = execCMD("omps -u admin -w 1234 --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
    }

    @Override
    public void deleteCredentials(CredentialsEntity credentials) throws Exception {
        StringBuilder xmlcmd = new StringBuilder();
        xmlcmd.append("<delete_credential credential_id='" + credentials.getUuid() + "'/>");

        String xmlString = execCMD("omps -u admin -w 1234 --xml='" + xmlcmd + "'");
        Document doc = getDocument(xmlString);
        Element root = doc.getRootElement();
        judgeStatus(root);
    }
}
